package HOT100;

/**
 * 删除链表倒数第n个节点
 * @author 是阿秋啊
 * @date 2022/08/01 22:32
 **/
public class num19 {
    // 思路
    // 先使用快慢指针锁定删除节点位置
    // 在定义一个前驱节点，用来连接
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode dummyHead = new ListNode(-1);
        ListNode fast = head,low = head;
        for(int i = 0; i < n; i++) {
            if(fast == null){
                return null;
            }
            fast = fast.next;
        }
        dummyHead.next = head;
        ListNode pre = dummyHead;
        while(fast != null) {
            low = low.next;
            fast = fast.next;
            pre = pre.next;
        }
        pre.next = low.next;
        return dummyHead.next;
    }
}
